<template>
  <div class="budget-page">
    <div class="page-header">
      <div class="page-title">添加成本预算</div>
      <el-button type="primary" plain size="small" icon="el-icon-back" @click="returnToProjectDetails">退出</el-button>
    </div>
    
    <!-- 步骤指示器 -->
    <div class="step-container">
      <el-steps :active="currentStep"  simple>
        <el-step title="数据录入" />
        <el-step title="附件上传" />
        <el-step title="数据确认" />
      </el-steps>
    </div>

    <!-- 根据当前步骤显示不同的内容 -->
    <div v-if="currentStep === 1">
      <!-- 第一步的表单内容 -->
      <div class="form-container">
        <el-form 
          ref="budgetForm"
          :model="formData"
          label-position="right"
          label-width="280px"
        >
          <div class="currency-label" >(单位：元)</div>
          
          <el-form-item label="不可预见费">
            <el-input 
              v-model="formData.unForeseenExpenses" 
              placeholder="输入不可预见费"
              class="budget-input"
            />
          </el-form-item>

          <el-form-item label="中标服务费">
            <el-input 
              v-model="formData.winningServiceFee" 
              placeholder="输入中标服务费"
              class="budget-input"
            />
          </el-form-item>

          <el-form-item label="标书制作费（标书文件费、公证费等）">
            <el-input 
              v-model="formData.biddingDocumentFee" 
              placeholder="输入标书制作费"
              class="budget-input"
            />
          </el-form-item>

          <el-form-item label="工程保险费（工程一切险、第三方责任险、意外伤害险等）">
            <el-input 
              v-model="formData.engineeringInsurance" 
              placeholder="输入工程保险费"
              class="budget-input"
            />
          </el-form-item>

          <el-form-item label="人员管理费：（13项=1%*国定浮调比例）">
            <el-input 
              v-model="formData.personnelManagementFee" 
              placeholder="输入人员管理费"
              class="budget-input"
            />
          </el-form-item>

          <el-form-item label="税金">
            <el-input 
              v-model="formData.taxes" 
              placeholder="输入税金"
              class="budget-input"
            />
          </el-form-item>
        </el-form>

        <!-- 底部按钮 -->
        <div class="form-footer">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>
    </div>

    <div v-if="currentStep === 2" class="upload-container">
      <!-- 预算明细选项卡 -->
      <div class="budget-tabs">       
        <ProjectTabsCost ref="childRef" :projectId="projectId" :formData="formData" />
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button>
      </div>
    </div>

    <!-- 第三步：数据确认 -->
    <div v-if="currentStep === 3" class="confirm-container">
      <div class="detail-table">
        <h2 class="table-title">工程项目成本预算明细表</h2>
        
        <div class="project-info">
          <span>项目名称：</span>
          <span class="unit-label">(单位：元)</span>
        </div>

        <el-table :data="confirmTableData" border>
          <el-table-column prop="name" label="明细" />
          <el-table-column prop="sequence" label="项次" width="100" align="center" />
          <el-table-column prop="budgetAmount" label="预算金额(元)" width="200" align="right">
            <template #default="scope">
              <span :class="{ 'blue-text': scope.row.isBlue }">{{ formData[scope.row.budgetAmount]}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="auditAmount" label="审核金额" width="200" align="right">
            <template #default="scope">
              <el-input
                v-model="formData[scope.row.auditAmount]"
                placeholder="请输入审核金额"
                size="small"
                :class="{ 'blue-input': scope.row.isBlue }"
              >
              </el-input>
            </template>
          </el-table-column> -->
        </el-table>
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep">确认并完成</el-button>
      </div>
    </div>

    <!-- 第四步：完成 -->
    <!-- <div v-if="currentStep === 4" class="complete-container">
      <div class="detail-table">
        <h2 class="table-title">工程项目成本预算明细表</h2>
        
        <div class="project-info">
          <span>项目名称：2021年度机电系统养护工程项目</span>
          <span class="unit-label">(单位：元)</span>
        </div>

        <el-table :data="confirmTableData" border>
          <el-table-column prop="name" label="明细" min-width="300" />
          <el-table-column prop="sequence" label="项次" width="80" align="center" />
          <el-table-column prop="budgetAmount" label="预算金额" width="180" align="right">
            <template #default="scope">
              <span :class="{ 'blue-text': scope.row.isBlue }">{{ scope.row.budgetAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="auditAmount" label="审核金额" width="180" align="right">
            <template #default="scope">
              <span>{{ formData[scope.row.auditAmount] || '0.00' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div> -->
  </div>
</template>

<script>
import ProjectTabsCost from "../cost/ProjectTabsCost"
import projectCostService from '@/api/cost/projectCostService'
import { ElNotification, ElMessageBox } from "element-plus";

export default {
  name: 'Budget',
  components:{ProjectTabsCost},
  data() {
    return {
      projectId: '',
      basisType: '',
      currentStep: 1,
      formData: {
        unForeseenExpenses: '',
        winningServiceFee: '',
        biddingDocumentFee: '',
        engineeringInsurance: '',
        personnelManagementFee: '',
        taxes: '',
        auditUnForeseenExpenses: '',
        auditWinningServiceFee: '',
        auditBiddingDocumentFee: '',
        auditEngineeringInsurance: '',
        auditPersonnelManagementFee: '',
        auditTaxes: '',
        auditEquipmentCost: '',
        auditConstructionCost: '',
        auditSafetyProductionCost: '',
        auditResearchFunding: '',
        auditOtherManagementFee: '',
        auditMiscellaneous: ''
      },
      tableData: [],
      confirmTableData: [
        { name: '不可预见费', sequence: '3', budgetAmount: 'unForeseenExpenses', auditAmount: 'auditUnForeseenExpenses' },
        { name: '中标服务费', sequence: '5', budgetAmount: 'winningServiceFee', auditAmount: 'auditWinningServiceFee' },
        { name: '标书制作费（标书文件费、公证费等）', sequence: '6', budgetAmount: 'biddingDocumentFee', auditAmount: 'auditBiddingDocumentFee' },
        { name: '工程保险费（工程一切险、第三方责任险、意外伤害险等）', sequence: '10', budgetAmount: 'engineeringInsurance', auditAmount: 'auditEngineeringInsurance' },
        { name: '人员管理费：（13项=1%*国定浮调比例）', sequence: '13', budgetAmount: 'personnelManagementFee', auditAmount: 'auditPersonnelManagementFee' },
        { name: '税金', sequence: '16', budgetAmount: 'taxes', auditAmount: 'auditTaxes' },
        { name: '附表一：设备（材料、软件）费', sequence: '8', budgetAmount: 'equipmentCost', auditAmount: 'auditEquipmentCost', isBlue: true },
        { name: '附表二：施工（服务）费', sequence: '9', budgetAmount: 'constructionCost', auditAmount: 'auditConstructionCost', isBlue: true },
        { name: '附表三：安全生产费、保通费等', sequence: '11', budgetAmount: 'safetyProductionCost', auditAmount: 'auditSafetyProductionCost', isBlue: true },
        { name: '附表四：科研费', sequence: '12', budgetAmount: 'researchFunding', auditAmount: 'auditResearchFunding', isBlue: true },
        { name: '附表五：其他管理费（项目租赁、车辆使用租赁费用、办公经费等）', sequence: '14', budgetAmount: 'otherManagementFee', auditAmount: 'auditOtherManagementFee', isBlue: true },
        { name: '附表六：其他（测定仪、法车等专业仪器设备租赁）', sequence: '15', budgetAmount: 'miscellaneous', auditAmount: 'auditMiscellaneous', isBlue: true },
   
        { name: '附表七：技术服务费', sequence: '16', budgetAmount: 'serviceFee', auditAmount: 'auditServiceFee', isBlue: true }
      ],
      savedFormData: {}, // 用于保存步骤2的数据
    }
  },
  created(){
    const { id, basisType } = this.$route.query
    if (id) {
      this.projectId = id
    } else {
      this.$message.error('项目ID不存在')
      this.returnToList()
    }
    
    if (basisType) {
      this.basisType = basisType
    }


    console.log("cesces",this.projectId)
    
    this.getInfo()
  },
  watch: {
    '$route.query.id': {
      handler(newVal) {
        if (newVal) {
          this.projectId = newVal;
        }
      },
      immediate: true // 立即执行一次，以便在组件创建时也能获取到数据
    }
  },
  methods: {
    getInfo(){
      // ProjectTabsCost.queryById({projectId:this.projectId}).then(res=>{
        
      // })
    },
    async nextStep() {
      if(this.currentStep === 1){
        if(JSON.stringify(this.savedFormData)!=='{}'){ 
          this.formData = { ...this.savedFormData };
        }
        this.formData.isPrev=false
        this.currentStep++;
      }else if (this.currentStep === 2) {
        try {
          // 弹出确认提示
          await ElMessageBox.confirm('确认该页面已完成，进入下一步操作？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          // 获取子组件的 inputForm 数据
          const inputFormData = this.$refs.childRef.getInputFormData();
    

          // 保存步骤2的数据
          this.savedFormData = { ...this.formData, ...inputFormData };
          this.formData.isPrev=false
          // 如果用户确认，继续执行下一步操作
          const resone = await this.$refs.childRef.nextCost();
          this.formData = resone;
          this.updateConfirmTableData();
          this.currentStep++;
        } catch (error) {
          // 用户取消或发生错误时的处理
          console.error('操作取消或失败:', error);
          this.$message.info('操作已取消');
        }
      } else if (this.currentStep === 3) {
        // 提交所有数据
        this.formData.isPrev=false
        this.saveSubmit();
      } else if (this.currentStep < 4) {
        this.formData.isPrev=false
        this.currentStep++;
      }
    },
    async prevStep() {
      if (this.currentStep === 3) {
        // 恢复步骤2的数据
        this.formData = { ...this.savedFormData };
   
        // 将数据传递回子组件
        // console.log("this.savedFormData",this.savedFormData, this.$refs.childRef)
        // this.$refs.childRef.setInputFormData(this.savedFormData);
      }else if(this.currentStep === 2){
        // const inputFormData = this.$refs.childRef.getInputFormData();  
        // this.savedFormData = { ...this.formData, ...inputFormData };
      
        this.formData = { ...this.savedFormData };
      }
      this.formData.isPrev=true
      if (this.currentStep > 1) {
        this.currentStep--;
      }
    },
       // 表单提交
       saveSubmit() {
        try {

       
          this.loading = true;
          // this.inputForm.project.id = this.projectId;
          // this.inputForm = { ...this.inputForm, ...this.formData }

          projectCostService.save({...this.formData,project:{id:this.formData.project.id}}).then((data) => {
            this.loading = false
            this.$message.success('保存成功');
            this.returnToProjectDetails()
            this.currentStep=0;

          }).catch((error) => {
            this.loading = false
            this.$message.error('提交失败，请重试');
          })
        } catch (error) {
          this.loading = false
          this.$message.error('提交失败，请重试');
        }
    },

    updateConfirmTableData() {
      // 格式化数字显示
      // this.confirmTableData = this.confirmTableData.map(item => ({
      //   ...item,
      //   budgetAmount: this.formatNumber(item.budgetAmount)
      // }));
    },
    formatNumber(value) {
      // 格式化数字为两位小数
      return parseFloat(value || 0).toFixed(2);
    },
    handleAuditInput(row) {
      // 将审核金额直接绑定到formData对应的字段
      this.formData[row.auditAmount] = row.inputValue;
    },
    async submitAllData() {
      // 这里处理最终的数据提交
      const submitData = {
        ...this.formData,
        // 可以添加其他需要提交的数据
      };
      // 调用API提交数据
    
    
          
      
      
    },
    returnToProjectDetails() {
      this.$router.push({
        path: '/projectDetails/projectDetails',
        query: { 
          id: this.projectId,
          basisType: this.basisType,
          tab:"budget"
        }
      })
    },
    returnToList() {
      this.$router.push('/project/ProjectMainList')
    }
  }
}
</script>

<style scoped lang="scss">
.budget-page {
  padding: 20px;
  background: #fff;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .page-title {
    font-size: 16px;
    font-weight: bold;
  }

  .step-container {
    margin: 20px 0 40px;
    padding: 20px;
    background: #f5f7fa;
  }

  .form-container {
    padding: 0 20px;
    max-width: 800px;
    margin: 0 auto;
    
    .currency-label {
      color: #909399;
      font-size: 14px;
      text-align: center;
      margin-bottom: 30px;
    }

    .budget-input {
      width: 300px;

     
    }

    .el-form-item {
      margin-bottom: 25px;
      display: flex;
      justify-content: center;
      
      :deep(.el-form-item__label) {
        font-weight: normal;
        color: #606266;
        width: 380px !important;
        text-align: right;
      }
      
      :deep(.el-form-item__content) {
        margin-left: 0 !important;
        width: 300px;
      }
    }
  }

  .form-footer {
    margin-top: 40px;
    text-align: center;
    
    .el-button {
      padding: 12px 25px;
      margin: 0 10px;
    }
  }

  .upload-container {
    // padding: 0 20px;

    .budget-tabs {
      margin-bottom: 20px;
      
      :deep(.el-tabs__item) {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        
        .el-icon-document {
          margin-right: 5px;
        }
      }
    }

    .operation-buttons {
      margin-bottom: 20px;
      
      .el-button {
        margin-right: 10px;
      }
    }

    :deep(.el-table) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: normal;
      }
      
      td {
        padding: 8px 0;
      }
    }
  }

  .confirm-container {
    padding: 0 20px;
    max-width: 1200px;
    margin: 0 auto;

    .detail-table {
      background: #f2f4f5;
      padding: 30px;
      border-radius: 4px;

      .table-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }

      .project-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 0 10px;

        .unit-label {
          color: #909399;
        }
      }

      :deep(.el-table) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: normal;
        }

        td {
          background-color: #F2F4F5;
        }

        .blue-text {
          color: #409EFF;
        }

        .el-input {
          
          .el-input__inner {
            text-align: right;
            padding-right: 8px;
            // background-color: #F2F4F5;
          }
          
          &.blue-input {
            .el-input__inner {
              color: #409EFF;
            }
          }
        }

        .el-input-group__append {
          padding: 0 8px;
          background-color: #F2F4F5;
          color: #909399;
        }
      }
    }
  }

  .complete-container {
    padding: 0 20px;
    max-width: 1200px;
    margin: 0 auto;

    .detail-table {
      background: #f2f4f5;
      padding: 30px;
      border-radius: 4px;

      .table-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }

      .project-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 0 10px;

        .unit-label {
          color: #909399;
        }
      }

      :deep(.el-table) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: normal;
        }

        td {
          background-color: #F2F4F5;
        }

        .blue-text {
          color: #409EFF;
        }

        .el-input {
          
          .el-input__inner {
            text-align: right;
            padding-right: 8px;
            // background-color: #F2F4F5;
          }
          
          &.blue-input {
            .el-input__inner {
              color: #409EFF;
            }
          }
        }

        .el-input-group__append {
          padding: 0 8px;
          background-color: #F2F4F5;
          color: #909399;
        }
      }
    }
  }
}
</style>
